package cn.edu.xmu.restfuldemo.dao;

import cn.edu.xmu.restfuldemo.mapper.GoodsPoMapper;
import cn.edu.xmu.restfuldemo.mapper.ProductPoMapper;
import cn.edu.xmu.restfuldemo.model.BO.Product;
import cn.edu.xmu.restfuldemo.model.PO.GoodsPo;
import cn.edu.xmu.restfuldemo.model.PO.GoodsPoExample;
import cn.edu.xmu.restfuldemo.model.PO.ProductPo;
import cn.edu.xmu.restfuldemo.model.PO.ProductPoExample;
import cn.edu.xmu.restfuldemo.model.VO.GoodsRetVo;
import cn.edu.xmu.restfuldemo.model.VO.GoodsVo;
import cn.edu.xmu.restfuldemo.model.VO.ProductRetVo;
import cn.edu.xmu.restfuldemo.model.VO.ProductVo;
import cn.edu.xmu.restfuldemo.util.RedisUtil;
import cn.edu.xmu.restfuldemo.util.ReturnObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Team3-5
 */
@Repository
public class ProductDao {
    @Autowired
    GoodsPoMapper goodsPoMapper;

    @Autowired
    ProductPoMapper productPoMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${restfuldemo.goodsSku.expiretime}")
    private long goodsTimeout;

    /**
     * 不加redis的商品 SKU 完整信息--根据货品获得货品和商品
     * @param id
     * @return
     */
    public ReturnObject<ProductRetVo> findProductRetVoByProductId(Long id){
        ProductPo productPo = productPoMapper.selectByPrimaryKey(id);
        GoodsPo goodsPo = goodsPoMapper.selectByPrimaryKey(productPo.getGoodsId());
        GoodsVo goodsVo = new GoodsVo(goodsPo);
        ProductVo productVo = new ProductVo(productPo);
        ProductRetVo productRetVo = new ProductRetVo(productVo.newProduct(),goodsVo.newGoods());
        return new ReturnObject<>(productRetVo);
    }

    /**
     * 加redis的商品 SKU 完整信息--根据货品获得货品和商品
     * @param id
     * @return
     */
    public ReturnObject<ProductRetVo> findProductRetVoByProductIdUsingRedis(Long id){
        List<ProductRetVo>retVos = null;
        String key = "product_goods_"+id;
        ProductRetVo productRetVo = (ProductRetVo) redisUtil.get(key);
        if (null != productRetVo){
            return new ReturnObject<>(productRetVo);
        }
        ProductPo productPo = productPoMapper.selectByPrimaryKey(id);
        GoodsPo goodsPo = goodsPoMapper.selectByPrimaryKey(productPo.getGoodsId());
        GoodsVo goodsVo = new GoodsVo(goodsPo);
        ProductVo productVo = new ProductVo(productPo);
        ProductRetVo productRetVo1 = new ProductRetVo(productVo.newProduct(),goodsVo.newGoods());
        redisUtil.set(key,  productRetVo1, goodsTimeout);
        return new ReturnObject<>(productRetVo1);
    }


}
